package com.vision.sales.sv.serv;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.vision.core.sv.util.CollectionUtils;

public class PeriodSalesReportParams extends SalesReportParams {

	String type;
	int year;
	List<Integer> months;
	Date date =  new Date();

	public PeriodSalesReportParams(HttpServletRequest req) {
		super(req);
		
		type = req.getParameter("type");
		if (type != null 
				&& !ReportConstants.MONTHLY.equalsIgnoreCase(type) 
				&& !ReportConstants.ANNUAL.equalsIgnoreCase(type)) {
			warnings.append("Type cannot be determined. Defaulting to annual.\n");
			type = ReportConstants.ANNUAL;
		}
		
		Calendar now = Calendar.getInstance();
		
		String sYear = req.getParameter("year");
		if (sYear != null)
		{
			try {
				year = Integer.parseInt(sYear);
			} catch (Exception e) {
				year = now.get(Calendar.YEAR);
				warnings.append("Failed to parse year: " + req.getParameter("year") + ". Using current year: " + year + "\n");
			}
		}
		
		String sDate = req.getParameter("date");
		if (sDate != null) {
			try {
				date = yyyyMMdd.parse(sDate);
			} catch (Exception e) {
				error = "Unable to parse start and end dates.";
			}
		}
		
		
		String sMonths = req.getParameter("months");
		if (sMonths != null)
			months = CollectionUtils.intsFromString(sMonths, ',');
		if (months == null || months.isEmpty()) {
			int mo = now.get(Calendar.MONTH) + 1;
			warnings.append("Month is empty. Using current month: " + mo + "\n");
			months = new ArrayList<Integer>();
			months.add(mo);
		}
		Collections.sort(months);
	}
	
	public boolean isAnnual() {
		return ReportConstants.ANNUAL.equalsIgnoreCase(type);
	}

}
